package com.bzyd.ss.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Configuration 表示当前类是一个配置类，类似于Spring xml文件
 * @EnableWebSecurity 表示启用Spring Security安全框架的功能
 * @EnableGlobalMethodSecurity 表示启用方法级别的认证
 *      prePostEnabled：默认是false
 *          true：表示可以使用@PreAuthorize、@PostAuthorize注解
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 设置内存账户信息
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder pe = getPasswordEncoder();
        auth.inMemoryAuthentication()
                .withUser("zhangsan")
                .password(pe.encode("123456"))
                .roles("normal")
                .authorities("user:create","user:find");
        auth.inMemoryAuthentication()
                .withUser("lisi")
                .password(pe.encode("123456"))
                .roles("normal")
                .authorities("order:find");
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password(pe.encode("admin"))
                .roles("normal","admin");

    }


    /**
     * 从Spring Security 5 开启需要设置密码加密算法
     */
    @Bean
    public PasswordEncoder getPasswordEncoder(){
        // 使用Spring Security 默认提供的强散列加密算法，也可以自己实现算法类
        return new BCryptPasswordEncoder();
    }
}
